<style scoped>
.container {
  width: 100%;
  height: 100%;
  background: white;
  overflow: auto;
  text-align: left;
}

.areaList {
  background-color: #fff !important;
}
</style>
<template>
  <div class="container">
    <van-nav-bar @click-left="back">
      <van-icon size="20" name="arrow-left" slot="left" color="rgb(150, 151, 153)"/>
      <p slot="title" style="font-size: 14px">{{ title }}</p>
    </van-nav-bar>
    <van-address-edit
        class="areaList"
        :area-list="areaList"
        :address-info="addressInfo"
        show-set-default
        show-search-result
        :save-button-text="save_btn"
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-detail="onChangeDetail"
    />
  </div>

</template>

<script>
import Vue from 'vue'
import {areaList} from '@vant/area-data'
import {NavBar, AddressEdit} from 'vant'
import {requestAddAddress, requestUpdateAddress} from "../../api/address";

Vue.use(NavBar)
Vue.use(AddressEdit)
export default {
  name: "AdressEdit",
  data() {
    return {
      addressInfo: {},
      searchResult: [],
      areaList,
      title: '',
      save_btn: '',
    }
  },
  created() {
    let {action} = this.$route.params
    switch (action) {
      case 'add':
        this.title = this.save_btn = '添加地址'
        break;
      case 'edit':
        this.title = this.save_btn = '修改地址'
        this.addressInfo = JSON.parse(localStorage.getItem('edit'))
        break;
    }
  },
  methods: {
    // 添加地址
    add(data) {
      var params = Object.assign({
        userid: localStorage.getItem('userid')
      }, data)
      console.log('save', params)
      requestAddAddress(params).then(res => {
        console.log(res)
        this.back()
        requestUpdateAddress(params).then(res=>{
          console.warn('双重保险',res)
        })
      })
      // 为了解决后端的bug

    },
    // 编辑地址
    edit(data) {
      console.log('修改地址=>', data)
      var params = Object.assign({
        userid: localStorage.getItem('userid')
      }, data)
      requestUpdateAddress(params).then(res=>{
        console.log(res)
        this.back()
      })
    },
    onSave(data) {
      if (this.save_btn === '添加地址') {
        this.add(data)
      } else {
        this.edit(data)
      }
    },
    onDelete() {

    },
    onChangeDetail() {

    },
    back() {
      this.$router.back()
    }
  }
}
</script>